package com.ctgu.project.mq;

import com.ctgu.project.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ListController
 * @Author Alex2
 * @Date 2025/2/28 16:33
 **/
@RequestMapping("/api/list")
@RestController
public class ListController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String REDIS_KEY_MQ_LIST = "mq:list:1001";

    // http://localhost:8080/api/list/producer/hello
    @GetMapping("producer/{message}")
    public ApiResult producer(@PathVariable String message) {
        stringRedisTemplate.opsForList().leftPush(REDIS_KEY_MQ_LIST, message);
        return ApiResult.success("生产新消息成功", message);
    }

    // http://localhost:8080/api/list/consumer
    @GetMapping("consumer")
    public ApiResult consumer() {
        String message = stringRedisTemplate.opsForList().leftPop(REDIS_KEY_MQ_LIST);
        if (message != null) {
            return ApiResult.success("消费成功", message);
        } else {
            return ApiResult.success("所有消息均已消费，消息队列为空");
        }
    }

    // http://localhost:8080/api/list/delayConsumer
    @GetMapping("delayConsumer")
    public ApiResult delayConsumer() {
        // 阻塞等待，超时时间 10 秒
        String message = stringRedisTemplate.opsForList().leftPop(REDIS_KEY_MQ_LIST, 10, TimeUnit.SECONDS);
        if (message != null) {
            return ApiResult.success("消费成功", message);
        } else {
            return ApiResult.success("等待超时或消息队列为空");
        }
    }
}